package edu.colorado.cs.correll.cudroplet.shaperecognition;

import java.awt.Shape;
import java.awt.geom.PathIterator;
import java.util.LinkedList;
import java.util.List;
import processing.core.PVector;

import com.vividsolutions.jts.awt.ShapeWriter;
import com.vividsolutions.jts.geom.Geometry;

public class GeometryUtil {

	public static List<Line> getLines(Geometry geometry) {
		List<Line> lines = new LinkedList<Line>();
		ShapeWriter shapeWriter = new ShapeWriter();
		Shape shape = shapeWriter.toShape(geometry);
		PathIterator pathIterator = shape.getPathIterator(null);
		PVector first = null;
		PVector last = null;
		while (!pathIterator.isDone()) {
			float[] coords = new float[6];
			int ret = pathIterator.currentSegment(coords);
			PVector curr = null;
			if (ret == PathIterator.SEG_MOVETO
					|| ret == PathIterator.SEG_LINETO) {
				curr = new PVector(coords[0], coords[1]);
			}
			if (first == null) {
				first = curr;
			}

			if (ret == PathIterator.SEG_LINETO || ret == PathIterator.SEG_CLOSE) {
				PVector a;
				PVector b;
				if (ret == PathIterator.SEG_LINETO) {
					a = last;
					b = curr;
				} else {
					a = curr;
					b = first;
				}
				lines.add(new Line(a, b));
			}

			if (ret == PathIterator.SEG_MOVETO
					|| ret == PathIterator.SEG_LINETO) {
				last = curr;
			}
			pathIterator.next();
		}
		return lines;
	}
}
